import React, { useState, useEffect } from 'react'
import {
  BarsOutlined, ClockCircleOutlined, DeleteOutlined, EllipsisOutlined,
  FileDoneOutlined, FilterOutlined, PlusOutlined, ReloadOutlined, SearchOutlined,
  VerticalAlignBottomOutlined, VerticalAlignTopOutlined
} from '@ant-design/icons';
import {Pagination ,Button, Flex, Input, Space, Form, Modal, Select, Tag, Cascader } from 'antd';
import type { TableColumnsType,PaginationProps } from 'antd';
import type { DataType } from '../utils/TS'
import Tables from '../components/Tables';
import '../utils/Home.css'
import instance from '../axios/request'
import SelectBumen from '../components/SelectBumen'
import SelectChengyuan from '../components/SelectChengyuan'
//表头数据
const columns: TableColumnsType<DataType> = [
  {
    title: '',
    width: 0,
    dataIndex: '', // 假设隐藏列为ID
    key: '',
    fixed: 'left',
  },
  { title: '客户编码', dataIndex: 'code', key: 'code' },
  { title: '客户名称', dataIndex: 'name', key: 'name' },
  {
    title: '客户分类', dataIndex: 'category', key: 'category',
    render: (_, { category }) => (
      <>
        <Tag color={category === '潜在客户' ? 'red' : category === '战略合作' ? 'blue' : 'green'}>{category}</Tag>
      </>
    ),
  },
  { title: '客户来源', dataIndex: 'source', key: 'source' },
  {
    title: '客户标签', dataIndex: 'label', key: 'label',
    render: (_, { label }) => (
      <>
        <Tag color={label === 'SMB' ? 'yellow' : label === 'ME' ? 'blue' : 'green'}>{label}</Tag>
      </>
    ),
  },
  { title: '结算期限', dataIndex: 'settlement', key: 'settlement' },
  { title: '信用额度/元', dataIndex: 'credit', key: 'credit' },
  { title: '销售负责人', dataIndex: 'responsibility', key: 'responsibility' },
  { title: '销售归属于部门', dataIndex: 'department', key: 'department' },
  { title: '客户地址', dataIndex: 'address', key: 'address' }, // 地址字段保留
  { title: '提交人', dataIndex: 'sub_name', key: 'sub_name' },
  { title: '提交时间', dataIndex: 'tijiao', key: 'tijiao' },
  { title: '更新时间', dataIndex: 'gengxin', key: 'gengxin' },
];

// 上面定义的类型
interface Contacts {
  // 联系人姓名
  contacts_name: string;
  // 联系人电话
  phone: string;
  // 职位
  position: string;
}
interface Finance {
  // 账户电话
  account_phone: string;
  // 添加时间
  added: string;
  // 银行
  bank: string;
  // 银行账户
  bank_account: string;
  // 类别
  categories: string;
  // 发票税号
  invoice_duty: string;
  // 发票抬头
  invoice_head: string;
  // 收票邮箱
  receive_email: string;
  // 收票电话
  receive_phone: string;
}
interface AddCustomerData {
  // 地址
  addres: string[];
  // 详细地址
  addres_detail: string;
  // 类别
  category: string;
  // 联系人
  contacts: Contacts[];
  // 信用
  credit: string;
  // 部门
  department: string;
  // 财务
  finance: Finance[];
  // 标签
  label: string;
  // 名称
  name: string;
  // 责任人
  responsibility: string;
  // 结算方式
  settlement: string;
  // 来源
  source: string;
}


export default function Home() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm<AddCustomerData>(); // 用于管理表单数据
  //表格数据
  const [dataSource, setdataSource] = useState<DataType[]>([])
  const [len, setlen] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10); // 每页显示条数，可根据需求调整
  const [paginatedDataSource, setPaginatedDataSource] = useState<DataType[]>([]); // 分页后的数据
  const showModal = () => {
    setIsModalOpen(true);
  };



  const [iscode, setIscode] = useState(0)
  const arr1 = ['财务信息', '联系人信息', '跟进记录', '销售订单']

  const [defaultContacts, setdefaultContacts] = useState([
    { id: 1, name: '', phone: '', position: '' },
  ])
  const [IsHovered, setIsHovered] = useState(false)

  const getData = () => {
    instance.get('/Custom/list').then(res => {
      setdataSource(res.data)
      setlen(res.data.length);
      // 初始化时进行第一次分页
      handlePagination(res.data, current, pageSize);
    })
  }
  const onFinish = (values: any) => {
    const data = {
      addres: values.addres,
      addres_detail: values.addres_detail,
      category: values.category,
      source: values.source,
      contacts: [
        {
          contacts_name: values.contacts_name,
          phone: values.phone,
          position: values.position,
        }
      ],
      credit: values.credit,
      department: values.department,
      finance: [
        {
          account_phone: values.account_phone,
          added: values.added,
          bank: values.bank,
          bank_account: values.bank_account,
          categories: values.categories,
          invoice_duty: values.invoice_duty,
          invoice_head: values.invoice_head,
          receive_email: values.receive_email,
          receive_phone: values.receive_phone,
        }
      ],
      receive_phone: values.receive_phone,
      label: values.label,
      name: values.name,
      responsibility: values.responsibility,
      settlement: values.settlement,
    }
    console.log(data)
    instance.post('/Custom/add_custom', data).then(res => {
      console.log(res.code);
      if (res.code === 200) {
        setIsModalOpen(false)
        getData()
      }
      // 处理响应数据

    })
  };

  const onChange: PaginationProps['onChange'] = (page) => {
    setCurrent(page);
    // 页码改变时重新分页
    handlePagination(dataSource, page, pageSize);
  };

  // 分页处理函数
  const handlePagination = (data: DataType[], currentPage: number, pageSize: number) => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const newData = data.slice(startIndex, endIndex);
    setPaginatedDataSource(newData);
  };
  useEffect(() => {
    getData()
  }, []);

  return (
    <>
      <Flex className='topTit' justify={'space-between'}>
        <Flex>
          <Button color="green" variant="solid" icon={<PlusOutlined />} onClick={() => {
            showModal()
          }}>添加</Button>
          <Button color="default" variant="link" icon={<VerticalAlignBottomOutlined />}>
            导入
          </Button>
          <Button color="default" variant="link" icon={<VerticalAlignTopOutlined />}>
            导出
          </Button>
          <Button color="default" variant="link" icon={<DeleteOutlined />}>
            删除
          </Button>
          <Button color="default" variant="link" icon={<ClockCircleOutlined />}>
            操作记录
          </Button>
        </Flex>
        <Flex>
          <Space.Compact size="large">
            <Input addonBefore={<SearchOutlined />} placeholder="large size" />
          </Space.Compact>
          <Button color="default" variant="link" icon={<FilterOutlined />}>
            操作记录
          </Button>
          <Button color="default" variant="link" icon={<FileDoneOutlined />} />
          <Button color="default" variant="link" icon={<BarsOutlined />} />
          <Button color="default" variant="link" icon={<ReloadOutlined />} />
          <Button color="default" variant="link" icon={<EllipsisOutlined />} />
        </Flex>
      </Flex>
      <Tables columns={columns} dataSource={paginatedDataSource} />
      <Pagination
        current={current}
        onChange={onChange}
        total={len}
        pageSize={pageSize} // 显示每页条数
        showSizeChanger // 显示每页条数切换器
        onShowSizeChange={(currentPage, newPageSize) => {
          setPageSize(newPageSize);
          handlePagination(dataSource, currentPage, newPageSize);
          setCurrent(currentPage);
        }}
      />
      <Modal
        title="客户"
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        destroyOnHidden={true}
        width={'40%'}
        style={{ height: '80vh' }}
        footer
      >
        <div style={{ height: '70vh', overflowY: 'scroll' }}>
          <div className='wrapperStyle'>
            <div className='titleStyle'>客户基本信息</div>
            <div className='underlineStyle'>
              <div className='solidUnderlineStyle'></div>
            </div>
          </div>
          <Form name="trigger1" style={{ maxWidth: 600 }} form={form} layout="vertical" autoComplete="off" onFinish={onFinish}>
            <Flex justify={'space-around'}>
              <Form.Item
                name="code"
                label="客户编码"
              >
                {/* 禁用 */}
                <Input placeholder="自动生成无需填写" disabled style={{ width: '280px' }} />
              </Form.Item>
              <Form.Item
                name="name"
                label="客户名称"
                rules={[{ required: true }]}
              >
                <Input style={{ width: '280px' }} />
              </Form.Item>
            </Flex>
            <Flex justify={'space-around'}>
              <Form.Item name="category" label="客户分类">
                <Select style={{ width: '280px' }}>
                  <Select.Option value="潜在客户">潜在客户</Select.Option>
                  <Select.Option value="成交客户">成交客户</Select.Option>
                  <Select.Option value="战略合作">战略合作</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item name="source" label="客户来源">
                <Select style={{ width: '280px' }}>
                  <Select.Option value="百度SEM">百度SEM</Select.Option>
                  <Select.Option value="转介绍">转介绍</Select.Option>
                  <Select.Option value="官网注册">官网注册</Select.Option>
                  <Select.Option value="销售自拓">销售自拓</Select.Option>
                </Select>
              </Form.Item>
            </Flex>
            <Flex justify={'space-around'}>
              <Form.Item name="label" label="客户标签">
                <Select style={{ width: '280px' }}>
                  <Select.Option value="KA">KA</Select.Option>
                  <Select.Option value="MA">MA</Select.Option>
                  <Select.Option value="SMB">SMB</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item style={{ width: '280px' }}>
              </Form.Item>
            </Flex>
            <Flex justify={'space-around'}>
              <Form.Item name="settlement" label="结算期限">
                <Select style={{ width: '280px' }}>
                  <Select.Option value="月结">月结</Select.Option>
                  <Select.Option value="季结">季结</Select.Option>
                  <Select.Option value="现结">现结</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item name="credit" label="借用额度/元 ">
                <Input style={{ width: '280px' }} />
              </Form.Item>
            </Flex>
            <Flex justify={'space-around'}>
              <Form.Item name="responsibility" label="销售负责人 ">
                <SelectChengyuan chengyuan={(value: any) => form.setFieldsValue({ responsibility: value })} />
              </Form.Item>
              <Form.Item name="department" label="销售归属部门 ">
                <SelectBumen bumen={(value: any) => form.setFieldsValue({ department: value })} />
              </Form.Item>
            </Flex>
            <Flex justify={'space-around'}>
              <Form.Item name="addres" label="客户地址">
                <Cascader
                  style={{ width: '280px' }}
                  options={[
                    {
                      value: 'zhejiang',
                      label: 'Zhejiang',
                      children: [{ value: '北京市', label: '昌平区' }],
                    },
                  ]}
                />
              </Form.Item>

              <Form.Item name="addres_detail" label="">
                <Input.TextArea style={{ width: '280px' }} placeholder='请填写详细地址' />
              </Form.Item>
            </Flex>
            <div className='tableBox'>
              {
                arr1.map((item, index) => {
                  return (
                    <div className={iscode == index ? 'style1 tableBoxStyle' : 'tableBoxStyle'} key={index} onClick={() => {
                      setIscode(index)
                    }}>{item}</div>
                  )
                })
              }
            </div>
            <div style={{ display: iscode == 0 ? '' : 'none' }}>
              <Flex justify={'space-around'}>
                <Form.Item name="invoice_head" label="发票抬头">
                  <Input style={{ width: '280px' }} />
                </Form.Item>
                <Form.Item name="invoice_duty" label="发票税号">
                  <Input style={{ width: '280px' }} />
                </Form.Item>
              </Flex>
              <Flex justify={'space-around'}>
                <Form.Item name="categories" label="税种">
                  <Select style={{ width: '280px' }}>
                    <Select.Option value="纸质专票">纸质专票</Select.Option>
                    <Select.Option value="纸质普票">纸质普票</Select.Option>
                    <Select.Option value="电子专票">电子专票</Select.Option>
                    <Select.Option value="电子普票">电子普票</Select.Option>
                    <Select.Option value="全电专票">全电专票</Select.Option>
                    <Select.Option value="全电普票">全电普票</Select.Option>
                    <Select.Option value="无需开票">无需开票</Select.Option>
                  </Select>
                </Form.Item>
                <Form.Item name="added" label="增值税税率%">
                  <Input style={{ width: '280px' }} />
                </Form.Item>
              </Flex>
              <Flex justify={'space-around'}>
                <Form.Item name="account_phone" label="开户电话">
                  <Input style={{ width: '280px' }} />
                </Form.Item>
                <Form.Item name="receive_email" label="收票邮箱">
                  <Input style={{ width: '280px' }} />
                </Form.Item>
              </Flex>
              <Flex justify={'space-around'}>
                <Form.Item name="bank" label="开户银行">
                  <Select style={{ width: '280px' }}>
                    <Select.Option value="中国银行">中国银行</Select.Option>
                    <Select.Option value="招商银行">招商银行</Select.Option>
                    <Select.Option value="建设银行">建设银行</Select.Option>
                    <Select.Option value="工商银行">工商银行</Select.Option>
                  </Select>
                </Form.Item>
                <Form.Item name="bank_account" label="银行账户">
                  <Input style={{ width: '280px' }} />
                </Form.Item>
              </Flex>
            </div>
            <div style={{ display: iscode == 1 ? '' : 'none' }}>
              <Flex justify={'space-around'}>
                <Form.Item name="contacts_name" label="联系人姓名">
                  <Input style={{ width: '180px' }} />
                </Form.Item>
                <Form.Item name="phone" label="联系人手机">
                  <Input style={{ width: '180px' }} />
                </Form.Item>
                <Form.Item name="position" label="联系人职位">
                  <Input style={{ width: '180px' }} />
                </Form.Item>
              </Flex>
              <div className="other-contact-section">
                <div className="section-title">其他联系人信息</div>
                <table className="contact-table">
                  <thead>
                    <tr>
                      <th></th>
                      <th>联系人姓名</th>
                      <th>联系人手机</th>
                      <th>联系人职位</th>
                    </tr>
                  </thead>
                  <tbody>
                    {defaultContacts.map((contact) => (
                      <tr key={contact.id}>
                        <td onMouseEnter={() => setIsHovered(true)}
                          onMouseLeave={() => setIsHovered(false)}>
                          {
                            IsHovered ? <Button color="red" variant="link" icon={<DeleteOutlined />} onClick=
                              {() => {
                                setdefaultContacts((prevContacts) =>
                                  prevContacts.filter((c) => c.id !== contact.id)
                                );
                              }}
                            /> :
                              contact.id
                          }
                        </td>
                        <td>
                          <input
                            type="text"
                            placeholder="请输入姓名"
                            v-model={contact.name}
                          />
                        </td>
                        <td>
                          <input
                            type="text"
                            placeholder="请输入手机号"
                            v-model={contact.phone}
                          />
                        </td>
                        <td>
                          <input
                            type="text"
                            placeholder="请输入职位"
                            v-model={contact.position}
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                <Button color="green" variant="link" icon={<PlusOutlined />} onClick={() => {
                  const id = defaultContacts.length - 1;
                  let ide = 0;
                  if (id == -1) {
                    ide = 0;
                  } else {
                    ide = defaultContacts[id].id;
                  }
                  setdefaultContacts((prevContacts) => [...prevContacts, { id: ide + 1, name: '', phone: '', position: '' }]);
                }}>
                  添加
                </Button>
                <Button color="green" variant="link" icon={<FileDoneOutlined />} >快速填报</Button>
              </div>
            </div>
            <Flex style={{ display: iscode == 2 ? '' : 'none' }}>2</Flex>
            <Flex style={{ display: iscode == 3 ? '' : 'none' }}>3</Flex>

            <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        </div>
      </Modal>
    </>
  )
}
